/**
 * 
 */
package mblog.web.interceptor;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import mblog.core.pojos.Post;
import mblog.core.pojos.Tag;
import mblog.web.interceptor.bean.NavDataMap;
import mtons.modules.pojos.Page;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.faxsun.core.pojos.enums.PostType;
import com.faxsun.core.pojos.enums.TagType;
import com.faxsun.core.service.AggregationService;
import com.faxsun.core.service.LiveInteractionService;
import com.faxsun.core.service.PostService;
import com.faxsun.core.service.TagService;
import com.faxsun.core.service.WechatService;
import com.faxsun.core.utils.PreviewHtmlUtils;
import com.faxsun.pojos.TagAggregation;

/**
 * 
 * 导航数据拦截器
 * 
 */
public class NavDataInterceptor extends HandlerInterceptorAdapter {
	
    private static final int productShowSize = 4;
    
    private static final int newsShowSize = 6;
    
    private static final int summarySize = 40;
    
    private static final int newsSummarySize = 60;

    private static final Logger log = LoggerFactory.getLogger(NavDataInterceptor.class);

    @Autowired
    private TagService tagService;

    @Autowired
    protected AggregationService productAggregation;

    @Autowired
    protected PostService postService;

    @Autowired
    protected WechatService wechatService;

    @Autowired
    protected LiveInteractionService liveInteractionService;
    
    //public static final String navDataMapToken = "FaxsunNavData";
    public static final String navProDataToken = "FaxsunNavDataPro";
    public static final String navNewsDataToken = "FaxsunNavDataNews";
    public static final String navZhiboDataToken = "FaxsunNavDataZhibo";
    

	@SuppressWarnings("unchecked")
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		HttpSession session = request.getSession();
		String visit = request.getRequestURL().toString();		
        
        if(visit != null && !visit.isEmpty()){
            String key = session.getId();            
            
            Object bean = NavDataMap.navDatas.get(key);//session.getAttribute(navDataMapToken);
            try {
                if (bean == null) {
                    bean = new HashMap<String, Object>();
                } 
                
                List<ProductNav> proNavs = getNavProductList();
                List<ProductNav> newsNavs = getNavNewsList();
                ZhiboNav zhiboNav = getNavZhibo();
                
                //session.setAttribute(navProDataToken, proNavs);                
                //session.setAttribute(navNewsDataToken, newsNavs);               
                //session.setAttribute(navZhiboDataToken, zhiboNav); 
                
                ((HashMap<String, Object>)bean).put(navProDataToken, proNavs);                
                ((HashMap<String, Object>)bean).put(navNewsDataToken, newsNavs);                
                ((HashMap<String, Object>)bean).put(navZhiboDataToken, zhiboNav);
                
                NavDataMap.navDatas.put(key, bean);
                
            }catch(Throwable t){
                log.error("fetch data for navigation bar error at url:" + visit, t);
            }           
        }
        
		return true;
	}
	
	private List<ProductNav> getNavProductList(){

        Page pageNavProList = new Page();
        pageNavProList.setMaxResults(productShowSize);
        List<Tag> navProductList = tagService.listTags(TagType.PRODUCT, pageNavProList);
        List<ProductNav> ret = new ArrayList<ProductNav>(navProductList.size());
        for(Tag t : navProductList){
            Page p = new Page(1);
            p.setMaxResults(1);
            TagAggregation ta = productAggregation.aggregateEvulationsByTag(p, t);      
            List<Post> posts = ta.getEvaluations();
            if(posts != null && posts.size() > 0){
               t.setPost(posts.get(0));                
            }
            ret.add(new ProductNav(t));
        }
        
        return ret;
	}
    
    private List<ProductNav> getNavNewsList(){

        Page recentNews = new Page();
        recentNews.setMaxResults(newsShowSize);        
        
        List<Post> navNewsList = postService.findRecentPosts(recentNews, PostType.INFO);
        List<ProductNav> ret = new ArrayList<ProductNav>(navNewsList.size());
        for(Post p : navNewsList){
            ret.add(new ProductNav(p));
        }
        
        return ret;
    }
    
    private ZhiboNav getNavZhibo(){
        int liveCnt = wechatService.cntAllLive();
        long viewerCnt = liveInteractionService.getAllLiveViewer();
        return new ZhiboNav(liveCnt, viewerCnt);
    }
	
	public class ProductNav implements Serializable{
	    /**
		 * 
		 */
		private static final long serialVersionUID = -6490614151011734362L;
		Long   id;
	    String defaultImageUrl;
	    String name;
	    String summary;
	    
	    ProductNav(Tag tag){
	        this.id = tag.getId();
	        this.defaultImageUrl = tag.getProduct().getDefaultImageUrl();
	        this.name = tag.getName();
	        if(tag.getPost() != null){
	           this.summary = PreviewHtmlUtils.truncateHTML(tag.getPost().getSummary(), summarySize);	            
	        }
	    }
        
        ProductNav(Post post){
            this.id = post.getId();
            this.defaultImageUrl = post.getSnapshot().getOriginal();
            this.name = post.getTitle();
            this.summary = PreviewHtmlUtils.truncateHTML(post.getSummary(), newsSummarySize);   
        }
	    
        public Long getId() {
            return id;
        }
        public void setId(Long id) {
            this.id = id;
        }
        public String getDefaultImageUrl() {
            return defaultImageUrl;
        }
        public void setDefaultImageUrl(String defaultImageUrl) {
            this.defaultImageUrl = defaultImageUrl;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getSummary() {
            return summary;
        }
        public void setSummary(String summary) {
            this.summary = summary;
        }
	    
	}
	
	public class ZhiboNav{
	    int liveCnt;
	    long viewerCnt;
	    
	    ZhiboNav(int channelCnt, long viewerCnt){
	        this.liveCnt = channelCnt;
	        this.viewerCnt = viewerCnt;
	    }
	    
        public int getLiveCnt() {
            return liveCnt;
        }
        public void setLiveCnt(int channelCnt) {
            this.liveCnt = channelCnt;
        }
        public long getViewerCnt() {
            return viewerCnt;
        }
        public void setViewerCnt(long viewerCnt) {
            this.viewerCnt = viewerCnt;
        }
	    
	}

}
